package com.bilibili.gateway.filters;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author HuangRongFu
 * 2021/11/28 星期日7:42 下午
 */

/**
 * 网关统一鉴权:看用户是否登录,判断是否存在token
 * netflix: 网关zuul order 与springcloud gateway是一样的效果
 */
@Component
@Slf4j
//Ordered作用,定义顺序,spring框架通用
public class AuthFilter implements GlobalFilter, Ordered {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //白名单列表
    @Value("${gateway.excludedUrls}")
    private List<String> excludedUrls;


    /**
     * 鉴权逻辑
     *
     * @param exchange 交换机:获取request response
     * @param chain    过滤链
     * @Return: Mono<Void>
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //获取请求对象 和 响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //过滤白名单
        //获取请求的url地址 uri包含http://ip:port
        String requestPath = request.getURI().getPath();
        log.info("请求了地址:" + requestPath);

        //如果是白名单列表
        if (excludedUrls.contains(requestPath)) {

            //放行
            return chain.filter(exchange);
        }

        //从请求对象的请求头中获取token
        String token = request.getHeaders().getFirst("Authorization");

        //token 有值
        if (StringUtils.isNotEmpty(token)) {

            //后台管理系统请求过来是带上的 "Bearer "
            token = token.replace("Bearer ", "");

            //拼接redis中的key
            String tokenKey = "TOKEN_" + token;

            //从redis中取值
            String loginUserJson = stringRedisTemplate.opsForValue().get(tokenKey);

            //有值
            if (StringUtils.isNotEmpty(loginUserJson)) {

                return chain.filter(exchange);
            }
        }

        log.error("用户未登录");

        //没值 报401
        response.setStatusCode(HttpStatus.UNAUTHORIZED);

        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

        Map<String, Object> responseData = new HashMap<>();
        responseData.put("errCode", 401);
        responseData.put("errMessage", "用户未登录");

        DataBuffer dataBuffer = response.bufferFactory().wrap(JSON.toJSONBytes(responseData));

        return response.writeWith(Mono.just(dataBuffer));
    }

    /**
     * 返回过滤链中执行的顺序
     * 值越小越优先执行
     * @return
     */
    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}
